package com.fxhy.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.baby.utils.VerifySignUtil;
import com.fxhy.config.WeChatConfig;
import com.fxhy.service.UserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.api.WxMpService;

@Controller
@Slf4j
@Api(value="微信接口")
@RequestMapping("wechat")
public class WeChatApi {
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private WxMpService wxMpService;
	
	@ApiOperation("微信网页授权")
	@RequestMapping(value="authorize",method= {RequestMethod.GET,RequestMethod.POST})
	public String authorize(){
		String redirectUrl = wxMpService.oauth2buildAuthorizationUrl(WeChatConfig.callBackUrl, WxConsts. OAuth2Scope.SNSAPI_USERINFO, null);
		log.info("微信网页授权....,地址:{}",redirectUrl);
		return "redirect:"+redirectUrl;
	}
	
	@ApiOperation("获取微信OpenId")
	@GetMapping("getOpenId")
	public String getOpenId(RedirectAttributes attr,@RequestParam("code") String code,
			@RequestParam("state") String returnUrl) throws Exception{
		WxMpOAuth2AccessToken wxMpOAuth2AccessToken = new WxMpOAuth2AccessToken();
		try {
			wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
		} catch (WxErrorException e) {
			log.error("微信网页授权异常{}",e);
			throw new Exception();
		}
		String openId = wxMpOAuth2AccessToken.getOpenId();
		WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
		log.info("微信登录获取的信息:{}",wxMpUser.toString());
		log.info("获取openId:{}....",openId);
		
		String token = "";
//		String token = JWTUtil.sign(userInfo.getUserId()+"",userInfo.getPassword());
		return "redirect:"+WeChatConfig.goToIndexUrl+"?userId=&openId="+openId+"&token="+token;
	}
	
	
	/**
	 * 微信服务器认证地址
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@ApiOperation("微信服务器认证地址")
	@RequestMapping(value="checkWebcatId",method= {RequestMethod.GET,RequestMethod.POST})
	public void checkWebcatId(HttpServletRequest request, HttpServletResponse response) throws Exception{
		
	    boolean isGet = request.getMethod().toLowerCase().equals("get");
        PrintWriter print;
        if (isGet) {
            // 微信加密签名
            String signature = request.getParameter("signature");
            // 时间戳
            String timestamp = request.getParameter("timestamp");
            // 随机数
            String nonce = request.getParameter("nonce");
            // 随机字符串
            String echostr = request.getParameter("echostr");
            log.info("微信服务器认证地址.....加密签名:{},时间戳:{},随机数:{},随机字符串:{}",signature,timestamp,nonce,echostr);
            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
            boolean b = VerifySignUtil.checkSignature(signature, timestamp, nonce);
            if (signature != null && VerifySignUtil.checkSignature(signature, timestamp, nonce)) {
                try {
                    print = response.getWriter();
                    print.write(echostr);
                    print.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
	    }
	}
}
